// 用户信息相关的 key
export const USER_INFO_KEY = 'user-info'

// 用户信息接口
export interface UserInfo {
  userName: string
  headshot: string
  phoneNumber: string
  email: string
  realName: string
  sex: number
  passwordComplexity: number | null // 用户密码强度，没有则为3最低
  token: string
}

// 获取用户信息
export const getUserInfo = (): UserInfo | null => {
  const userInfo = localStorage.getItem(USER_INFO_KEY)
  if (userInfo) {
    try {
      return JSON.parse(userInfo) as UserInfo
    } catch (error) {
      console.error('解析用户信息失败:', error)
      return null
    }
  }
  return null
}

// 设置用户信息
export const setUserInfo = (userInfo: UserInfo): void => {
  localStorage.setItem(USER_INFO_KEY, JSON.stringify(userInfo))
}

// 清除用户信息
export const clearUserInfo = (): void => {
  localStorage.removeItem(USER_INFO_KEY)
}

// 获取 token
export const getToken = (): string => {
  const userInfo = getUserInfo()
  return userInfo?.token || ''
}

// 设置 token
export const setToken = (token: string): void => {
  const userInfo = getUserInfo() || ({} as UserInfo)
  userInfo.token = token
  setUserInfo(userInfo as UserInfo)
}

// 移除 token
export const removeToken = (): void => {
  const userInfo = getUserInfo()
  if (userInfo && userInfo.token) {
    const { token, ...rest } = userInfo
    setUserInfo(rest as UserInfo)
  }
}

// 判断用户是否已登录
export const isLoggedIn = (): boolean => {
  return !!getToken()
}
